var areaLayerIndex = 0;
$(function (){
    $("#jqGrid").jqGrid({
        url: baseURL + 'farm/list',
        datatype: "json",
        colModel: [
			{ label: 'dataId',hidden:true, name: 'dataId', index: 'dataId', width: 50, key: true },
			{ label: '所属经营主体', name: 'subjectName', width: 120 },
			{ label: '基地名称', name: 'name', width: 120 },
			{ label: '种养方式', name: 'speciesName', width: 80},
			{ label: '基地类型', name: 'typeName', width: 80},
			{ label: '规模', name: 'area', width:40 },
			{ label: '单位', name: 'unitName', width: 30 },
			{ label: '地址', name: 'address',width:100 },
			{ label: '联系人', name: 'linkMan', width:50},
			{ label: '状态', name: 'status', width:40, formatter: function(value, options, row){
				return value === 0 ? '<span class="label label-danger">禁用</span>' : '<span class="label label-success">正常</span>';
			}},
			{ label: '创建时间', name: 'createTime', index: 'create_time', width:50}
        ],
		viewrecords: true,
        height: (pageInfo().height-130),
        rowNum: 15,
		rowList : [15,50,99],
        loadtext : '<img src="../../statics/plugins/layer/skin/default/loading-1.gif" style="margin-right:10px;"/>正在加载,请稍候……',
        loadui: "enable",/*Disable,禁用loadtext*/
        rownumbers: true,
        rownumWidth: 25,
        autowidth:true,
        multiselect: true,
        pager: "#jqGridPager",
        beforeRequest : function(){},
        loadComplete : function(data){
            if(data.code == 0){
                return data;
            }else if(data.code == 205){
                invalidAccess();
            }else{
                layer.alert(data.msg);
            }
        },
        loadError : function(xhr,status,error){},
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames : {
            page:"page", 
            rows:"limit", 
            order: "order"
        },
        gridComplete:function(){
        	//隐藏grid底部滚动条
        	$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" }); 
        }
    });

    thisPage = {
        initDom : function(){
            this.getTypeArea();
            this.getTypeSales();
            this.getTypePlant();
            this.getTypeUnit();
            $('#tryThis').on('click',function(){
                layer.close(areaLayerIndex);
                window.open('../../statics/location/index.html','_blank').location;
            });
        },
        getAreaData : function(pid,containerDom,selectDom,labelText){
            selectArea.getData(baseURL + 'sysarea/getListArea',pid,containerDom,selectDom,labelText);
        },
        /**基地类型*/
        getTypeArea : function(){
            ajaxQuery(baseURL + 'farm/getTypeArea',{},function(data){
                setDataSelect('选择基地类型','#type_id',data.data,'value','text');
            });
        },
        /**基地类型*/
        getTypeSales : function(){
            ajaxQuery(baseURL + 'farm/getTypeSales',{},function(data){
                setDataSelect('选择销售方式','#sales_id',data.data,'value','text');
            });
        },
        /**种养类型*/
        getTypePlant : function(){
            ajaxQuery(baseURL + 'farm/getTypePlant',{},function(data){
                setDataSelect('选择种养类型','#species_id',data.data,'value','text');
            });
        },
        /**单位*/
        getTypeUnit : function(){
            ajaxQuery(baseURL + 'farm/getTypeUnit',{},function(data){
                setDataSelect('选择计量单位','#unit_id',data.data,'value','text');
            });
        }
    }
    thisPage.initDom();
});

var setting = {
    data: {
        simpleData: {
            enable: true,
            idKey: "deptId",
            pIdKey: "parentId",
            rootPId: -1
        },
        key: {
            url:"nourl"
        }
    }
};
var ztree;
var vm = new Vue({
	el:'#witapp',
	data:{
		showList: true,
		title: null,
		farm: {
			status:1,
			deptId:null,
            deptName:null
		},
		q:{
            key: null
        }
	},
	methods: {
		query: function () {
			vm.reload();
		},
        viewInfo: function (event){
			var dataId = getSelectedRow();
			if(dataId == null){
				return ;
			}
            var _this = this;
            ajaxQuery(baseURL + "farm/info/"+dataId,{},function(data){
                if(data.code == 0){
                    data = data.data;
                    var html = '';
                    html += _this.fitter('主体账号',data.user_name);
                    html += _this.fitter('基地名称',data.name);
                    if(data.create_time != undefined){
                        html += _this.fitter('创建时间',data.create_time);
                    }
                    if(data.type_name != undefined){
                        html += _this.fitter('基地类型',data.type_name);
                    }
                    if(data.sales_name != undefined){
                        html += _this.fitter('销售方式',data.sales_name);
                    }
                    if(data.longs != undefined){
                        html += _this.fitter('基地纬度',data.longs);
                    }
                    if(data.lat != undefined){
                        html += _this.fitter('基地纬度',data.lat);
                    }
                    if(data.city != undefined){
                        html += _this.fitter('区域位置',(data.province_name != undefined ? data.province_name : "")+(data.city_name != undefined ? data.city_name : "")+(data.county_name != undefined ? data.county_name : "")+(data.villages_name != undefined ? data.villages_name : "")+(data.hamlet_name != undefined ? data.hamlet_name : ""));
                    }
                    if(data.address != undefined){
                        html += _this.fitter('详细地址',data.address);
                    }
                    if(data.area != undefined){
                        html += _this.fitter('基地面积',data.area +'亩');
                    }
                    if(data.species_name != undefined){
                        html += _this.fitter('种养种类',data.species_name);
                    }
                    if(data.unit_name != undefined){
                        html += _this.fitter('计量单位',data.unit_name);
                    }
                    if(data.link_man != undefined){
                        html += _this.fitter('联系人',data.link_man);
                    }
                    if(data.link_tel != undefined){
                        html += _this.fitter('联系电话',data.link_tel);
                    }
                    if(data.graphics != undefined && data.graphics.length > 0){
                        html += '<div class="col-sm-2 control-label">基地图片</div>';
                        html += '<div class="col-sm-10" style="border-bottom:1px solid #999;margin-bottom:14px;padding-bottom:14px;">';
                        html += "<div class=\"col-sm-12\">";
                        var graphic = data.graphics.split(',');
                        for (var i = 0; i<graphic.length; i++){
                            var imageUrl = graphic[i];
                            if(imageUrl != undefined && imageUrl.length > 0){
                                html+='<a class="col-sm-12" style="color:#459df5;margin-left: -30px;" title="点击查看基地图片" target="_blank" href="../..'+imageUrl+'">基地图片'+(i+1)+'</a>';
                            }
                        }
                        html+="</div>";
                        html += '</div>';
                    }
                    if(data.status != undefined){
                        html += _this.fitter('基地状态',data.status == 1 ? "正常" : "禁用");
                    }
                    if(data.description != undefined){
                        html += _this.fitter('基地描述',data.description);
                    }
                    $('#div_view_layer .form-horizontal').empty().html(html);
                    viewDom('查看','#div_view_layer',['600px','500px']);
                }else{
                    alert(data.msg);
                }
            });
		},
        fitter : function(label,value){
            var html = '<div class="form-group">';
            html += '<div class="col-sm-2 control-label">'+label+'</div>';
            html += '<div class="col-sm-10" style="border-bottom:1px solid #999;">';
            html += '<div style="margin-top:6px;">'+value+'</div>';
            html += '</div>';
            html += '</div>';
            return html;
        },
        addFarm : function(){
            this.openDialog();
        },
        editFarm : function(){
            var dataId = getSelectedRow();
            if(dataId == null){
                return ;
            }
		    var _this = this;
		    ajaxQuery(baseURL + "farm/info/"+dataId,{},function(data){
                if(data.code == 0){
                    _this.openDialog(dataId,data.data);
                }else{
                    alert(data.msg);
                }
            });
        },
        openDialog : function(kid,map){
		    var url = 'farm/save';
		    var title = '添加基地信息';
            if(kid != null && kid.length >0){
                url = 'farm/update?data_id='+kid;
                title = '编辑基地信息';
            }
            addOrEdit(title,'#div_farm_dialog',['600px','520px'],function(indexLayero,layero){
                var name = $('#name').val();
                var type_id = $('#type_id').val();
                var type_name = $('#type_id').find("option:selected").text();
                var sales_id = $('#sales_id').val();
                var sales_name = $('#sales_id').find("option:selected").text();
                var longs = $('#farmLongs').val();
                var lat = $('#farmLat').val();
                var province_id = $('#farmProvinceId').val();
                var province_name = $('#farmProvinceId').find("option:selected").text();
                var city = $('#farmCityId').val();
                var city_name = $('#farmCityId').find("option:selected").text();
                var county = $('#farmCountyId').val();
                var county_name = $('#farmCountyId').find("option:selected").text();
                var villages = $('#farmTownsId').val();
                var villages_name = (villages != null && villages.length > 0) ? $('#farmTownsId').find("option:selected").text() : null;
                var hamlet = $('#farmVallageId').val();
                var hamlet_name = (hamlet != null && hamlet.length > 0) ? $('#farmVallageId').find("option:selected").text() : null;
                var address = $('#address').val();
                var area = $('#area').val();
                var species_id = $('#species_id').val();
                var species_name = $('#species_id').find("option:selected").text();
                var unit_id = $('#unit_id').val();
                var unit_name = $('#unit_id').find("option:selected").text();
                var link_man = $('#link_man').val();
                var link_tel = $('#link_tel').val();
                var framImages = $('#framImages').val();
                var status = $("input[name='status']:checked").val();
                var description = $('#description').val();
                if(name == null || name.length <= 0){
                    alert("请填写基地名称");
                    return;
                }
                if(type_id == null || type_id.length <= 0){
                    alert("请选择基地类型");
                    return;
                }
                if(sales_id == null || sales_id.length <= 0){
                    alert("请选择销售方式");
                    return;
                }
                if(longs == null || longs.length <= 0){
                    alert("请选择经度");
                    return;
                }
                if(lat == null || lat.length <= 0){
                    alert("请选择纬度");
                    return;
                }
                if(kid == null || kid.length <=0){
                    if(province_id == null || province_id.length <= 0){
                        alert("请选择省|市");
                        return;
                    }
                    if(city == null || city.length <= 0){
                        alert("请选择市|区");
                        return;
                    }
                    if(county == null || county.length <= 0){
                        alert("请选择区|县|市");
                        return;
                    }
                    if(villages == null || villages.length <= 0){
                        alert("请选择乡|镇|社区");
                        return;
                    }
                }
                if(address == null || address.length <= 0){
                    alert("尚未填写基地详细地址");
                    return;
                }
                if(area == null || area.length <= 0){
                    alert("请填写基地面积");
                    return;
                }
                if(species_id == null || species_id.length <= 0){
                    alert("请选择种养种类");
                    return;
                }
                if(link_man == null || link_man.length <= 0){
                    alert("联系人不能为空");
                    return;
                }
                if(link_tel == null || link_tel.length <= 0){
                    alert("联系电话不能为空");
                    return;
                }
                if(kid == null || kid.length <=0){
                    if(framImages == null || framImages.length <= 0){
                        alert("选择基地图片便于展示");
                        return;
                    }
                }
                var params = {
                    name : name,
                    type_id : type_id,
                    type_name : type_name,
                    sales_id : sales_id,
                    sales_name : sales_name,
                    longs : longs,
                    lat : lat,
                    province_id : province_id,
                    province_name : province_name,
                    city : city,
                    city_name : city_name,
                    county : county,
                    county_name : county_name,
                    villages : villages,
                    villages_name : villages_name,
                    hamlet : hamlet,
                    hamlet_name : hamlet_name,
                    address : address,
                    area : area,
                    species_id : species_id,
                    species_name : species_name,
                    unit_id : unit_id,
                    unit_name : unit_name,
                    link_man : link_man,
                    link_tel : link_tel,
                    framImages : framImages,
                    status : status,
                    description : description,
                }
                var files = document.getElementById("framImages").files;
                if(files.length > 3){
                    alert("基地图片不能大于3张");
                    return;
                }
                var formData = new FormData();
                for(var key in params){
                    formData.append(key,params[key]);
                }
                for(var index in files){
                    formData.append("image"+index,files[index]);
                }
                formSubmit(url,formData,function(data){
                    if(0 == data.code){
                        layer.close(indexLayero);
                        vm.reload();
                    }else{
                        alert(data.msg);
                    }
                });
            });
            thisPage.getAreaData('0','#div_area_import','.clsProvince','选择省|市');
            if(kid != null && kid.length > 0){
                $("#showImages").css("display","");
                this.renderDom(map);
            }else{
                $("#showImages").css("display","none");
                $('#showImages').empty();
            }
        },
        renderDom : function(map){
            for(var k in map){
                var v = map[k]+'';
                if(k == 'status'){
                    $("input[name='status'][value="+v+"]").attr("checked",true);
                }else if(k == 'longs'){
                    $('#farmLongs').val(v);
                }else if(k == 'lat'){
                    $('#farmLat').val(v);
                }else if(k == 'graphics'){
                    var html = "<div class=\"col-sm-12\">";
                    var graphic = v.split(',');
                    for (var i = 0; i<graphic.length; i++){
                        html+='<div class="col-sm-2"></div>';
                        html+='<a class="col-sm-10" style="color:#459df5;" title="点击查看基地图片" target="_blank" href="../..'+graphic[i]+'">基地图片'+(i+1)+'</a>';
                    }
                    html+="</div>";
                    $('#showImages').empty().append(html);
                }else{
                    $('#'+k).val(v);
                }
            }
        },
        getLocation : function(){
            $('#div_longs').text('经度:0.0');
            $('#div_lat').text('纬度:0.0');
            areaLayerIndex = addOrEdit('标注选择地理位置[<span style="color:#01aaed">点击选取经纬度</span>]','#div_select_area',['800px','540px'],function(index,layero){
                var lng = $('#hidden_longs').val();
                var lat = $('#hidden_lat').val();
                $('#farmLongs').val(lng);
                $('#farmLat').val(lat);
                layer.close(index);
            });
        },
		del: function (event) {
			var dataIds = getSelectedRows();
			if(dataIds == null){
				return;
			}
			confirm('确定要删除选中的记录？', function(){
			    ajaxExecute(baseURL + "farm/delete",JSON.stringify(dataIds),function(data){
                    if(data.code == 0){
                        vm.reload();
                    }else{
                        alert(data.msg);
                    }
			    });
			});
		},
		reload: function (event) {
			vm.showList = true;
			var page = $("#jqGrid").jqGrid('getGridParam','page');
			$("#jqGrid").jqGrid('setGridParam',{ 
				postData:{'key': vm.q.key},
                page:page
            }).trigger("reloadGrid");
		}
	}
});